package com.nhjf.admin.controller.teachers;

import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.controller.BaseController;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.command.system.ModifyRoleCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.common.util.StringUtil;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.Organization;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.OrganizationHasStudent;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.qo.studnet.StudentQo;
import com.nhjf.pojo.qo.system.OrganizationQo;
import com.nhjf.pojo.qo.system.RoleQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.OrganizationHasStudentQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.student.StudentService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.OrganizationHasStudentService;
import com.nhjf.service.teachers.TeachersService;

import antlr.StringUtils;

import org.apache.shiro.session.InvalidSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/stu")
public class StudentController extends BaseController {

	@Autowired
	private StudentService studentService;
	@Autowired
	private OrganizationHasStudentService organizationHasStudentService;
	@Autowired
	private TeachersService teachersService;
	@Autowired
	private UserService userService;
	@Autowired
	private OperationLogService operationLogService;

	@RequestMapping(value = "/sutlist")
	public String queryRoleList(HttpServletResponse response,HttpServletRequest request, Model model,@ModelAttribute OrganizationHasStudentQo stuQo,@RequestParam(value="page", defaultValue="1")Integer page) {
		try {
			if (stuQo == null) {
				stuQo = new OrganizationHasStudentQo();
			}
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role role=new Role();
			while(iter.hasNext()) {
				role=iter.next();
				break;
			}

			if("1".equals(role.getNumber())) {
				StudentQo sqo=new StudentQo();
				if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getPhone())) {
					sqo.setPhone(stuQo.getPhone());
				}
				if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getName())) {
					sqo.setName(stuQo.getName());
				}	
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				pagination.setCondition(sqo);
				pagination.setPageNo(page);
				model.addAttribute("stuQo", stuQo);
				pagination = studentService.queryPagination(pagination);
				model.addAttribute("pagination", pagination);
				model.addAttribute("type", 1);
				return "/student/student_list.html";

			}else if("2".equals(role.getNumber()) || "3".equals(role.getNumber())) {
				TeachersQo qo= new TeachersQo();
//				if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getPhone())) {
//					stuQo.setPhone(stuQo.getPhone());
//				}
//				if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getName())) {
//					stuQo.setName(stuQo.getName());
//				}
//				stuQo.setStudentId(qo.getId());
				stuQo.setIsCxdqjgxs(2);
 				qo.setUserId(user.getId());
				qo.setSeachOrganization(true);
				Teacher teacher= teachersService.queryUnique(qo);
				if(teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null ) {
					stuQo.setOrganizationId(teacher.getTraininginstitution().getId());
				}else {
						response.sendRedirect(request.getContextPath()+"/login");
				}
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				pagination.setCondition(stuQo);
				pagination.setPageNo(page);
				pagination = organizationHasStudentService.queryPagination(pagination);
				model.addAttribute("pagination", pagination);
				model.addAttribute("stuQo", stuQo);
				model.addAttribute("type",2);
				return "/student/student_list.html";
				//			stuQo.setOrganizationId(teacher.getTraininginstitution().getId());
				//			List<OrganizationHasStudent> list= serivce.queryList(stuQo);
				//			model.addAttribute("sList",list);
				//			return "/role/role_list.html";

			}else  {
				return "/error/error.html";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "/error/error.html";
		} 
	}
	/**
	 * 删除学生
	 * @param request
	 * @param response
	 * @param role
	 * @param id
	 * @param model
	 * @param qo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/student_delete")
	public String delStu(HttpServletRequest request,HttpServletResponse response ,@ModelAttribute ModifyRoleCommand role,String id,Model model,StudentQo qo) {

		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}else {
				if("1".equals(roles.getNumber())) {
					return "只有老师和机构管理员有此权限哦!";
				} else if("3".equals(roles.getNumber()) || "2".equals(roles.getNumber())) {
					TeachersQo tqo=new TeachersQo();
					tqo.setUserId(user.getId());
					Teacher teacher=teachersService.queryUnique(tqo);
					OrganizationHasStudentQo organizationHasStudentQo=new OrganizationHasStudentQo();
					organizationHasStudentQo.setOrganizationId(teacher.getTraininginstitution().getId());//找到机构id
					organizationHasStudentQo.setStudentId(Long.parseLong(id));
					OrganizationHasStudent organizationHasStudent =organizationHasStudentService.queryUnique(organizationHasStudentQo);
					organizationHasStudentService.deleteById(organizationHasStudent.getId());
					OperationLog operationLog=new OperationLog();
					operationLog.setOperationType(1);
					operationLog.setOperationDescription("删除学生!");
					operationLog.setUserId(user);
					operationLog.setOperationTime(new Date());
					operationLog.setOperationUserName(user.getUserName());
					operationLogService.save(operationLog);
					return "200";
				}
			}

		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
		return "200";
	}
	@RequestMapping("/stutoadd")
	public String stutoadd() {

		return "/student/student_add.html";
	}
	/**
	 * 添加学生
	 * @param request
	 * @param response
	 * @param phone
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/stu_add",method=RequestMethod.POST)
	public String studd(HttpServletRequest request,HttpServletResponse response,String phone,Model model) {

		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if(StringUtil.isNotNull(phone)) {
				/*				OrganizationHasStudentQo ohsQo=new OrganizationHasStudentQo();
				ohsQo.getOrganization().setId(oQo.getId());
				ohsQo.getStudent().setId(qo.getId());
				ohsQo=serivce.save(ohsQo);*/
				UserQo userqo=new UserQo();
				userqo.setUserName(phone);
				User users=userService.queryUnique(userqo);
				//				users.getId();
				if(null == users) {
					return "500";
				}else {
					StudentQo suQo=new StudentQo();
					suQo.setUserid(users.getId());
					Student stu= studentService.queryUnique(suQo);
					if(stu==null) {
						return "500";
					}
					System.out.println(stu.getName());
					TeachersQo tqo=new TeachersQo();
					tqo.setUserId(user.getId());
					tqo.setSeachOrganization(true);
					tqo.setSeachUser(true);
					Teacher teacher=teachersService.queryUnique(tqo);
					//					OrganizationQo oQo=new OrganizationQo();
					System.out.println(teacher.getTraininginstitution());
					System.out.println(teacher.getTraininginstitution().getId());
					if(teacher!=null && teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null) {
						OrganizationHasStudentQo organizationHasStudentQo=new OrganizationHasStudentQo();
						organizationHasStudentQo.setOrganizationId(teacher.getTraininginstitution().getId());
						organizationHasStudentQo.setStudentId(stu.getId());
						OrganizationHasStudent organizationHasStudent= organizationHasStudentService.queryUnique(organizationHasStudentQo);
						if(organizationHasStudent==null) {
							OrganizationHasStudent ohs=new OrganizationHasStudent();
							ohs.setStudent(stu);
							Organization oiz =new Organization();
							oiz.setId(teacher.getTraininginstitution().getId());
							ohs.setOrganization(oiz);
							int i= organizationHasStudentService.ohsAdd(ohs);
							if(i==1) {
								OperationLog operationLog=new OperationLog();
								operationLog.setOperationType(2);
								operationLog.setOperationDescription("添加学生!");
								operationLog.setUserId(user);
								operationLog.setOperationTime(new Date());
								operationLog.setOperationUserName(user.getUserName());
								operationLogService.save(operationLog);
								return "200";
							}else {
								model.addAttribute("500");
								return "501";
							}
						}else {
							return "201";
						}
					}else {
						response.sendRedirect(request.getContextPath()+"/login");
					}
				}

			}else  {
				return "500";
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "501";
	}
	@RequestMapping("/stutoview")
	public String stutoview(HttpServletRequest request,HttpServletResponse response,String id,StudentQo qo,Model model) {
		try {
			SysProperties sysProperties=SysProperties.getInstance();
			//			 String filePath=sysProperties.get("imagePath")+"teacher/"+name+"."+extension;
			String filePahts=sysProperties.get("webPath")+"/img/";
			model.addAttribute("filePahts",filePahts);
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Student stu= studentService.get(Long.parseLong(id));
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}else{
				if(null!=stu ) {
					model.addAttribute("stu",stu);
					return "/student/student_view.html";
				} 
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "/student/student_view.html";
	}
}
